// DOM元素
const amountInput = document.getElementById('amount');
const currencySelect = document.getElementById('currency');
const descriptionInput = document.getElementById('description');
const orderIdInput = document.getElementById('order-id-input');
const createPaymentBtn = document.getElementById('create-payment');
const paymentElementContainer = document.getElementById(
  'payment-element-container'
);
const submitPaymentBtn = document.getElementById('submit-payment');
const paymentMessage = document.getElementById('payment-message');
const paymentLogs = document.getElementById('payment-logs');
const cancelPaymentBtn = document.getElementById('cancel-payment');
const cancelContainer = document.getElementById('cancel-container');
const orderInfoContainer = document.getElementById('order-info');
const orderIdElement = document.getElementById('order-id');
const orderDescriptionElement = document.getElementById('order-description');
const orderAmountElement = document.getElementById('order-amount');
const manualFormContainer = document.getElementById('manual-form');

// Stripe对象和元素
let stripe;
let elements;
let clientSecret;
let currentOrderId = null;
let returnUrl = null;

// 获取URL参数
function getUrlParam(name) {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(name);
}

// 初始化页面
document.addEventListener('DOMContentLoaded', async () => {
  // 检查URL中是否有订单ID
  const orderId = getUrlParam('orderId');
  if (orderId) {
    currentOrderId = orderId;
    log(`检测到订单ID: ${orderId}`);

    try {
      // 尝试从服务器获取订单信息
      const response = await fetch(`/api/order/${orderId}/status`);

      if (response.ok) {
        const orderData = await response.json();

        // 如果订单已存在，显示订单信息
        if (orderData) {
          // 从URL获取订单数据，或使用服务器返回的数据
          displayOrderInfo(
            orderId,
            getUrlParam('description') ||
              orderData.description ||
              `订单 ${orderId}`,
            getUrlParam('amount') || orderData.amount
          );

          // 自动创建支付意向
          autoCreatePayment(orderId);
        }
      } else {
        log(`无法获取订单信息: ${orderId}`);
      }
    } catch (error) {
      log(`获取订单信息出错: ${error.message}`);
    }

    // 记录返回URL
    returnUrl = getUrlParam('returnUrl');
    if (returnUrl) {
      log(`检测到返回URL: ${returnUrl}`);
    }
  }
});

// 显示订单信息
function displayOrderInfo(orderId, description, amount) {
  // 设置订单信息
  orderIdElement.textContent = orderId;
  orderDescriptionElement.textContent = description || '未提供描述';

  // 格式化金额显示
  const formattedAmount = amount
    ? parseFloat(amount) / 100 + ' ' + currencySelect.value.toUpperCase()
    : '未提供金额';
  orderAmountElement.textContent = formattedAmount;

  // 显示订单信息区域，隐藏手动表单
  orderInfoContainer.classList.remove('hidden');

  // 如果有完整的订单信息，隐藏手动表单
  if (orderId && description && amount) {
    manualFormContainer.classList.add('hidden');

    // 填充表单值以便后续使用
    amountInput.value = parseFloat(amount) / 100;
    descriptionInput.value = description;
  }
}

// 自动创建支付意向
async function autoCreatePayment(orderId) {
  try {
    // 尝试从URL参数获取金额和描述
    const amount = getUrlParam('amount');
    const currency = getUrlParam('currency') || 'cny';
    const description = getUrlParam('description') || `订单 ${orderId}`;

    if (!amount) {
      log('缺少金额参数，无法自动创建支付');
      return;
    }

    log(
      `自动创建支付意向: ${
        parseFloat(amount) / 100
      } ${currency.toUpperCase()} (订单ID: ${orderId})`
    );

    // 调用后端API创建支付意向
    const response = await fetch('/create-payment-intent', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        amount: amount,
        currency,
        description,
        orderId,
      }),
    });

    if (!response.ok) {
      throw new Error('创建支付意向失败');
    }

    const data = await response.json();
    log('支付意向创建成功');

    // 初始化Stripe
    clientSecret = data.clientSecret;
    stripe = Stripe(data.publishableKey);

    // 创建支付元素
    elements = stripe.elements({
      clientSecret,
      appearance: {
        theme: 'stripe',
      },
    });

    // 挂载支付元素
    const paymentElement = elements.create('payment');
    paymentElement.mount('#payment-element');
    log('支付表单已加载');

    // 显示支付表单和取消按钮
    paymentElementContainer.classList.remove('hidden');
    cancelContainer.classList.remove('hidden');
  } catch (error) {
    console.error('错误:', error);
    log(`自动创建支付错误: ${error.message}`);
    showMessage(`创建支付失败: ${error.message}`, true);
  }
}

// 日志函数
function log(message) {
  const timestamp = new Date().toLocaleTimeString();
  paymentLogs.textContent += `[${timestamp}] ${message}\n`;
  paymentLogs.scrollTop = paymentLogs.scrollHeight;
}

// 显示错误信息
function showMessage(message, isError = false) {
  paymentMessage.textContent = message;
  paymentMessage.className = isError ? 'error-message' : 'success-message';
}

// 创建支付意向
createPaymentBtn.addEventListener('click', async () => {
  try {
    // 获取表单数据
    const amount = parseFloat(amountInput.value);
    const currency = currencySelect.value;
    const description = descriptionInput.value;
    const orderId = currentOrderId || orderIdInput.value;

    // 验证金额
    if (isNaN(amount) || amount <= 0) {
      showMessage('请输入有效金额', true);
      return;
    }

    // 按照Stripe要求转换为最小货币单位（分）
    const amountInCents = Math.round(amount * 100);

    log(
      `创建支付意向: ${amount} ${currency.toUpperCase()}${
        orderId ? ` (订单ID: ${orderId})` : ''
      }`
    );

    // 调用后端API创建支付意向
    const response = await fetch('/create-payment-intent', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        amount: amountInCents,
        currency,
        description,
        orderId,
      }),
    });

    if (!response.ok) {
      throw new Error('创建支付意向失败');
    }

    const data = await response.json();
    log('支付意向创建成功');

    // 初始化Stripe
    clientSecret = data.clientSecret;
    stripe = Stripe(data.publishableKey);

    // 创建支付元素
    elements = stripe.elements({
      clientSecret,
      appearance: {
        theme: 'stripe',
      },
    });

    // 挂载支付元素
    const paymentElement = elements.create('payment');
    paymentElement.mount('#payment-element');
    log('支付表单已加载');

    // 显示支付表单和取消按钮
    paymentElementContainer.classList.remove('hidden');
    cancelContainer.classList.remove('hidden');
  } catch (error) {
    console.error('错误:', error);
    log(`错误: ${error.message}`);
    showMessage(`创建支付失败: ${error.message}`, true);
  }
});

// 提交支付
submitPaymentBtn.addEventListener('click', async () => {
  try {
    log('正在处理支付...');
    submitPaymentBtn.disabled = true;

    // 构建返回URL
    let finalReturnUrl =
      returnUrl || `${window.location.origin}/payment-success.html`;

    // 如果有订单ID，将其添加到成功页面的查询参数中
    if (currentOrderId) {
      const separator = finalReturnUrl.includes('?') ? '&' : '?';
      finalReturnUrl += `${separator}orderId=${currentOrderId}`;
    }

    // 确认支付
    const { error } = await stripe.confirmPayment({
      elements,
      confirmParams: {
        return_url: finalReturnUrl,
      },
      redirect: 'if_required',
    });

    // 处理错误
    if (error) {
      log(`支付错误: ${error.message}`);
      showMessage(`支付失败: ${error.message}`, true);
      submitPaymentBtn.disabled = false;
      return;
    }

    // 支付成功（如果没有重定向）
    log('支付成功!');
    showMessage('支付成功!', false);

    // 如果有返回URL且没有重定向，手动跳转
    if (finalReturnUrl) {
      log(`正在跳转到: ${finalReturnUrl}`);
      setTimeout(() => {
        window.location.href = finalReturnUrl;
      }, 1500);
    }

    // 隐藏支付表单
    paymentElementContainer.classList.add('hidden');
    cancelContainer.classList.add('hidden');
  } catch (error) {
    console.error('支付错误:', error);
    log(`支付错误: ${error.message}`);
    showMessage(`支付失败: ${error.message}`, true);
    submitPaymentBtn.disabled = false;
  }
});

// 取消支付
cancelPaymentBtn.addEventListener('click', () => {
  // 如果有返回URL，跳转回去并添加取消状态
  if (returnUrl) {
    const separator = returnUrl.includes('?') ? '&' : '?';
    const cancelUrl = `${returnUrl}${separator}status=cancelled&orderId=${
      currentOrderId || ''
    }`;
    log(`取消支付，返回: ${cancelUrl}`);
    window.location.href = cancelUrl;
  } else {
    // 否则重置表单
    log('取消支付');
    paymentElementContainer.classList.add('hidden');
    cancelContainer.classList.add('hidden');

    // 如果是从订单链接进入的，刷新页面
    if (currentOrderId) {
      window.location.href = '/';
    }
  }
});
